const {
  friendshipActivityDetail,
  friendshipActivityMemberList,
  getBase64,
  filePreview
} = require('../../../../api/index');
const {
  friendshipActivityCollect,
  friendshipActivityCancelCollect,
  checkCollect
} = require('../../../api/collect');
const {
  friendshipActivitySignUp
} = require('../../../../api/fraternity');
const {
  formatTime2,
  countdownFn,
  joinBase64
} = require('../../../../utils/util');

// pages/active/detail/index.js
Page({
  data: {
    id: '',
    isCollcet: false,
    page: {
      pageNumber: 1,
      pageSize: 6,
      friendshipActivityId: ''
    },
    countdown: '',
    total: 0,
    detail: {},
    personList: [], //  报名人员列表
    formData: {
      targetId: '',
      title: '',
      realName: ""
    }
  },
  //  提交
  async onSubmit() {

    wx.showModal({
      title: '确认报名',
      content: '确认报名后不可取消，您是否确定报名',
      success: async (res) => {
        if (res.confirm) {
          const {
            friendshipAssociationId,
            id
          } = this.data.detail;
          const {
            errors = []
          } = await friendshipActivitySignUp({
            friendshipAssociationId,
            friendshipActivityId: id
          });

          if (errors.length > 0) {
            return;
          }

          const success_back_url = `${ '/packageA/pages/active/manage/index?id=' + friendshipAssociationId }`;
          wx.setStorageSync('success_back_url', success_back_url);
          //  跳转到成功页面
          wx.navigateTo({
            url: '/packageA/pages/success/index?type=active_signup'
          });

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //  路径跳转
  onJump(event) {
    const {
      url
    } = event.currentTarget.dataset;
    wx.navigateTo({
      url
    });
  },
  /*** 生命周期函数--监听页面加载 */
  async onLoad(options) {
    wx.showLoading({
      title: '加载中...'
    });
    this.data.id = options.id;
    fetchFriendshipActivityMemberList.call(this)
    await fetchFriendshipActivityDetail.call(this);
    setFormData.call(this);
    await initCollect.call(this);
    wx.hideLoading();
  },
  /*** 用户点击右上角分享 */
  onShareAppMessage() {},
  async onCollect() {
    //  点击 检查是否收藏过
    const res = await fetchCheckCollect.call(this);

    if (res) { //  说明收藏了
      await fetchPopularActivityCancelCollect.call(this);
    } else { // 说明未收藏
      await fetchPopularActivityCollect.call(this);
    }
  },
})

//  设置 formData
function setFormData() {
  this.data.formData.title = this.data.detail.title;
  this.data.formData.targetId = this.data.detail.id;
  this.data.formData.realName = wx.getStorageSync('userInfo')?.realName;
}

async function initCollect() {
  const res = await fetchCheckCollect.call(this);
  res ? this.setData({
    isCollcet: true
  }) : this.setData({
    isCollcet: false
  });
}

// 检查 是否被收藏
async function fetchCheckCollect(data) {
  const {
    errors = [],
      result,
  } = await checkCollect(this.data.formData);
  if (errors.length > 0) {
    return;
  }
  console.log(result)
  return result === '1'; //  判断是否收藏
}

//  收藏
async function fetchPopularActivityCollect(data) {
  const {
    errors = [],
      collect = false
  } = await friendshipActivityCollect(this.data.formData);
  if (errors.length > 0) {
    myToast('收藏失败', 'error');
    return;
  }
  this.setData({
    isCollcet: true
  });
  myToast('收藏成功', 'success');
}

//  取消收藏
async function fetchPopularActivityCancelCollect(data) {
  const {
    errors = [],
      result,
      collect = false
  } = await friendshipActivityCancelCollect(this.data.formData);
  if (errors.length > 0) {
    myToast('取消收藏失败', 'error');
    return;
  }

  //  改变图标的颜色
  this.setData({
    isCollcet: false
  });

  myToast('取消收藏成功', 'success');

}

//  弹窗封装
function myToast(title, icon, duration = 1000) {
  wx.showToast({
    title,
    icon,
    duration
  });
}

async function fetchFriendshipActivityDetail() {
  const {
    errors = [], friendshipActivity = {}
  } = await friendshipActivityDetail({
    id: this.data.id
  });
  if (errors.length > 0) {
    return;
  }
  this.setData({
    detail: setResult.call(this, friendshipActivity)
  });
}

async function fetchFriendshipActivityMemberList() {
  this.data.page.friendshipActivityId = this.data.id;
  const {
    errors = [], result = [], totalCount
  } = await friendshipActivityMemberList(this.data.page);
  this.setData({
    total: totalCount
  });

  if (errors.length > 0) {
    return;
  }
  this.setData({
    personList: await setResult2(result.slice(0, 6))
  });
}

//  处理头像
async function setResult2(data) {
  const _data = JSON.parse(JSON.stringify(data));

  await Promise.all(_data.map(async _s => {
    const avatar = joinBase64(await getBase64(_s.avatar));
    _s.avatar = avatar;
    return _s;
  }))

  return _data;
}

function setResult(data) {
  const _data = JSON.parse(JSON.stringify(data));

  _data.applyTime = formatTime2(_data.applyTime);
  _data.activityBeginTime = formatTime2(_data.activityBeginTime);
  _data.activityEndTime = formatTime2(_data.activityEndTime);
  _data.registrationBeginTime = formatTime2(_data.registrationBeginTime);
  _data.originRegistrationEndTime = _data.registrationEndTime;
  _data.registrationEndTime = formatTime2(_data.registrationEndTime);
  _data.activityPhoto = filePreview('/file/preview/' + _data.activityPhoto)

  //  倒计时
  const t = setInterval(() => {
    const res = countdownFn(_data.originRegistrationEndTime);
    if (res === -1) {
      this.setData({
        countdown: '活动已结束'
      });

      clearInterval(t);
      return;
    }
    this.setData({
      countdown: countdownFn(_data.originRegistrationEndTime)
    })
  }, 1000);

  return _data;
}